package com.ztmmm.module.qu.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ztmmm.common.consts.QuAnswerConstant;
import com.ztmmm.common.consts.QuTypeConstant;
import com.ztmmm.common.dto.PageDto;
import com.ztmmm.common.enums.ApiErrorEnum;
import com.ztmmm.common.vo.ApiRest;
import com.ztmmm.common.vo.PageResult;
import com.ztmmm.exception.ServiceException;
import com.ztmmm.module.qu.dto.QuSaveDto;
import com.ztmmm.module.qu.entity.Qu;
import com.ztmmm.module.qu.entity.QuAnswer;
import com.ztmmm.module.qu.entity.QuRepo;
import com.ztmmm.module.qu.mapper.QuAnswerMapper;
import com.ztmmm.module.qu.mapper.QuMapper;
import com.ztmmm.module.qu.mapper.QuRepoMapper;
import com.ztmmm.module.qu.service.IQuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztmmm.module.repo.entity.Repo;
import com.ztmmm.module.repo.mapper.RepoMapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Array;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.ztmmm.common.vo.ApiRest.success;

/**
 * <p>
 * 问题题目 服务实现类
 * </p>
 *
 * @author ztm
 * @since 2023-03-21
 */
@Service
@Slf4j
public class QuServiceImpl extends ServiceImpl<QuMapper, Qu> implements IQuService {
    @Autowired
    private QuMapper quMapper;
    @Autowired
    private QuAnswerMapper quAnswerMapper;
    @Autowired
    private QuRepoMapper quRepoMapper;
    @Autowired
    private RepoMapper repoMapper;
    @Override
    @Transactional
    public ApiRest add(QuSaveDto quSaveDto) {
        checkData(quSaveDto);
        Qu qu = new Qu();
        BeanUtil.copyProperties(quSaveDto,qu,true);
        qu.setId(IdWorker.getIdStr());
        qu.setCreateTime(new Date());
        this.baseMapper.insert(qu);
        List<QuAnswer> answers = quSaveDto.getAnswers();
        for (QuAnswer q : answers){
            q.setId(IdWorker.getIdStr());
            q.setQuId(qu.getId());
            quAnswerMapper.insert(q);
        }
        String[] repoIds = quSaveDto.getRepoIds();
        for (String r : repoIds) {
            QuRepo quRepo = new QuRepo();
            quRepo.setId(IdWorker.getIdStr());
            quRepo.setQuType(qu.getQuType());
            quRepo.setQuId(qu.getId());
            quRepo.setRepoId(r);
            quRepoMapper.insert(quRepo);
            repoMapper.updateRepoCount(r);
        }
        log.info("{}添加题目成功",new Date());
        return success();
    }
    @Transactional
    public ApiRest del(String quId){
        List<String> strings = quRepoMapper.selectByQid(quId);
        if (quId == null){
            throw new ServiceException("参数异常");
        }
        int i1 = quMapper.deleteById(quId);
        int i = quAnswerMapper.delByQid(quId);
        quRepoMapper.delByQid(quId);
        for (String string : strings) {
            repoMapper.updateRepoCount(string);
        }
        return ApiRest.success();
    }
    @Transactional
    public ApiRest delAll(String[] quIds){
        for (String quId : quIds) {
            List<String> strings = quRepoMapper.selectByQid(quId);
            if (quId == null){
                throw new ServiceException("参数异常");
            }
            quMapper.deleteById(quId);
            quAnswerMapper.delByQid(quId);
            quRepoMapper.delByQid(quId);
            for (String string : strings) {
                repoMapper.updateRepoCount(string);
            }
        }


        return ApiRest.success();
    }
    @Transactional
    public ApiRest edit(QuSaveDto quSaveDto){
        checkData(quSaveDto);
        Qu qu = new Qu();
        BeanUtil.copyProperties(quSaveDto,qu,true);
        qu.setUpdateTime(new Date());
        this.baseMapper.updateById(qu);
        List<QuAnswer> answers = quSaveDto.getAnswers();
        for (QuAnswer q : answers){
            quAnswerMapper.updateById(q);
        }
        String[] repoIds = quSaveDto.getRepoIds();
        quRepoMapper.delByQid(qu.getId());
        for (String r : repoIds) {

            QuRepo quRepo = new QuRepo();
            quRepo.setId(IdWorker.getIdStr());
            quRepo.setQuType(qu.getQuType());
            quRepo.setQuId(qu.getId());
            quRepo.setRepoId(r);
            quRepoMapper.insert(quRepo);
            repoMapper.updateRepoCount(r);
        }
        log.info("{}添加题目成功",new Date());
        return success();
    }

    @Override
    public PageResult<Qu> findPage(PageDto<Qu> dto) {
        if (dto == null){
            throw new ServiceException("参数异常");
        }
        if (dto.getNow() == 0){
            throw new ServiceException("参数异常");
        }
        IPage<Qu> page = new Page<>(dto.getNow(),dto.getSize());
        QueryWrapper queryWrapper = new QueryWrapper();
        //内容模糊查询
        if (dto.getWhere().getContent() !=null){
            queryWrapper.like("content",dto.getWhere().getContent());
        }
        //题目类型模糊查询
        if (dto.getWhere().getQuType() !=null){
            queryWrapper.like("qu_type",dto.getWhere().getQuType());
        }
        IPage<Qu> iPage = this.page(page,queryWrapper);

        PageResult<Qu> pageResult = new PageResult<>();
        pageResult.setPages(iPage.getPages());
        pageResult.setList(iPage.getRecords());
        pageResult.setTotal(iPage.getTotal());
        return pageResult;
    }

    @Override

    public ApiRest<Qu> selectByQid(String quId) {
        if (quId == null){
            throw new ServiceException("ID为空");
        }
        Qu qu = this.quMapper.selectById(quId);
        List<String> strings = this.quRepoMapper.selectByQid(quId);
        List<QuAnswer> quAnswers = this.quAnswerMapper.selectByQid(quId);
        String[] s = new String[strings.size()];
        for (int i = 0; i < strings.size(); i++) {
            s[i] = strings.get(i);
        }
        QuSaveDto quSaveDto = new QuSaveDto();
        BeanUtil.copyProperties(qu,quSaveDto,true);
        quSaveDto.setAnswers(quAnswers);
        quSaveDto.setRepoIds(s);
        return ApiRest.success(quSaveDto);
    }

    private void checkData(QuSaveDto qu) {


        if (StringUtils.isEmpty(qu.getContent())) {
            throw new ServiceException(ApiErrorEnum.QU_CONTENT_IS_NULL.getMsg());
        }


        if (CollectionUtils.isEmpty(Arrays.asList(qu.getRepoIds()))) {
            throw new ServiceException(ApiErrorEnum.QU_REPO_ATLEAST_ONE.getMsg());
        }

        List<QuAnswer> answers = qu.getAnswers();


        if (qu.getQuType() != QuTypeConstant.JDT && CollectionUtils.isEmpty(answers)) {
            throw new ServiceException(ApiErrorEnum.QU_HAS_ANSWER.getMsg());
        }


        int trueCount = 0;
        for (QuAnswer a : answers) {

            if (a.getIsRight() == null) {
                throw new ServiceException(ApiErrorEnum.ANS_HAS_RIGHT_OPT.getMsg());
            }

            if (StringUtils.isEmpty(a.getContent())) {
                throw new ServiceException(ApiErrorEnum.ANS_HAS_CONTENT.getMsg());
            }

            if (a.getIsRight() == QuAnswerConstant.RIGHT) {
                trueCount += 1;
            }
        }

        if (trueCount == 0) {
            throw new ServiceException(ApiErrorEnum.QU_HAS_RIGHT_ANSWER.getMsg());
        }


        //单选题
        if (qu.getQuType() ==  QuTypeConstant.RADIO  && trueCount > 1) {
            throw new ServiceException(ApiErrorEnum.QU_RADIO_HAS_MULTI_RIGHT_ANSWER.getMsg());
        }
        //判断题
        if (qu.getQuType() ==  QuTypeConstant.JUDGE  && trueCount > 1) {
            throw new ServiceException(ApiErrorEnum.QU_RADIO_HAS_MULTI_RIGHT_ANSWER.getMsg());
        }
        //多选题题
        if (qu.getQuType() ==  QuTypeConstant.MULTI  && trueCount <= 1) {
            throw new ServiceException(ApiErrorEnum.QU_MULTI_HAS_MULTI_RIGHT_ANSWER.getMsg());
        }

    }
}
